package com.hbnu.service;
import com.hbnu.client.FileClient;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPromise;
import io.netty.util.AttributeKey;
import java.util.ArrayList;

import static com.hbnu.enums.Status.host;
import static com.hbnu.enums.Status.port;


public class FileService {
    //处理结果
    public static final AttributeKey<ChannelPromise> PROMISE = AttributeKey.valueOf("promise");
    private final FileClient fileClient;
    public FileService(){
        fileClient = new FileClient();
    }

    //直接一直在后台
    public void close(){
        // 关闭客户端  异步关闭等
        fileClient.stop();
    }
    private Channel getChannel()  {
        try {
            return  fileClient.getBootstrap().connect(host, port).sync().channel();
        } catch (Exception e) {
           // println("文件服务器无法连接...");
            throw new RuntimeException("文件服务器无法连接...");
        }
    }


    public void deleteFile(ArrayList<String> paths) {
        try {
            Channel channel = getChannel();
            ChannelPromise promise = channel.newPromise();
            channel.attr(PROMISE).set(promise);// 将 promise 存储在 Channel 的属性中
            channel.writeAndFlush(paths);
            // 阻塞直到获取请求结果
            promise.sync();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException("文件删除异常...");
        }
    }
}